/**
 iTextUploader
 (C) 2008 Asgl (myselftdev@gmail.com)

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; version 2
 of the License.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
*/

/* Revision: $Id: FileUpload.m 12 2008-07-25 10:05:51Z myselftdev $ */

#import "FileUpload.h"

#include <openssl/md5.h>

#define UPLOAD_URL "http://youarchive.it/remote_upload.php"
//URL for testing purposes :)
//#define UPLOAD_URL "http://192.168.1.186/SMS/remote_upload.php"
#define APP_VERSION "0.2"

@implementation FileUpload

- (id) init 
{ 
	self = [super init] ; 
	
	username = @"";
	password = @"";
	
	return self ;
}

- (void) dealloc
{
	[username release];
	[password release];
	
	[super dealloc];
}

- (void) setUsername: (NSString*)usernameSet password: (NSString*)passwordSet
{
	[username autorelease];
	username = [usernameSet retain];
	
	[password autorelease];
	password = [passwordSet retain];
}

/*
 The following method is based on code from iFlickr.
 iFlickr is released under the terms of the GNU GPL version 2.
 Project site: http://code.google.com/p/iflickr/
 */


- (NSString *) uploadFile: (NSString*)uploadFilename
{
	if([username isEqualToString:@""] || [password isEqualToString:@""])
	{
		NSLog(@"Login data empty");
		return [[NSString alloc] initWithCString:"LOGIN EMPTY" encoding:NSASCIIStringEncoding];
	}
	
	NSURL *theURL = [NSURL URLWithString:@UPLOAD_URL];
	
	NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:1000.0f];
	[theRequest setHTTPMethod:@"POST"];
	
	NSString *POSTDataSeparator = @"-----------------------------7d8h2d6f60awe3er2ni8";
	NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",POSTDataSeparator];
	[theRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
	
	NSMutableData *cooked=[NSMutableData data];
	NSMutableDictionary *newparam=[[NSMutableDictionary alloc] init];
	
	NSData *fileData = [NSData dataWithContentsOfFile:uploadFilename];
	
	if(![fileData length])
	{
		return [[NSString alloc] initWithCString:"FATAL ERROR\nError reading file" encoding:NSASCIIStringEncoding];
	}
	
	unsigned char *fileMD5cString = MD5([fileData bytes], [fileData length], NULL);
	NSMutableString *fileMD5 = nil;
	short i;
	
	if (fileMD5cString)
	{			fileMD5 = [NSMutableString stringWithCapacity:32];		for (i = 0; i < MD5_DIGEST_LENGTH; i++)
		{			[fileMD5 appendFormat: @"%02x", (int)(fileMD5cString[i])];		}	}
	else
	{
		return [[NSString alloc] initWithCString:"CHECKSUM ERROR" encoding:NSASCIIStringEncoding];
	}
	if(!fileMD5)
	{
		return [[NSString alloc] initWithCString:"CHECKSUM ERROR" encoding:NSASCIIStringEncoding];
	}
	NSLog(@"sms.db checksum: %@", fileMD5);
	
	[newparam setObject:username forKey:@"username"];
	[newparam setObject:password forKey:@"password"];
	[newparam setObject:@"import" forKey:@"mode"];
	[newparam setObject:@APP_VERSION forKey:@"appversion"];
	[newparam setObject:fileMD5 forKey:@"md5"];
	
	NSArray *keys=[newparam allKeys];
	int c=[keys count];
	
	for (i=0; i<c; i++) {
		NSString *k=[keys objectAtIndex:i];
		NSString *v=[newparam objectForKey:k];
		
		NSString *addstr = [NSString stringWithFormat:
							@"--%@\r\nContent-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",
							POSTDataSeparator, k, v];
		[cooked appendData:[addstr dataUsingEncoding:NSUTF8StringEncoding]];
	}
	
	[newparam release];
	
	
	NSRange position = [uploadFilename rangeOfString:@"/" options:NSBackwardsSearch];
	NSString *filename = [uploadFilename substringFromIndex:(position.location + 1)];
	NSString *content_type = @"application/octet-stream";
	
	NSString *filename_str = [NSString stringWithFormat:
							  @"--%@\r\nContent-Disposition: form-data; name=\"dbfile\"; filename=\"%@\"\r\nContent-Type: %@\r\n\r\n",
							  POSTDataSeparator, filename, content_type];
	
	[cooked appendData:[filename_str dataUsingEncoding:NSUTF8StringEncoding]];
	[cooked appendData:fileData];
	NSString *endmark = [NSString stringWithFormat: @"\r\n--%@--", POSTDataSeparator];
	[cooked appendData:[endmark dataUsingEncoding:NSUTF8StringEncoding]];
	
	[theRequest setHTTPBody:cooked];
	
	NSURLResponse *theResponse = NULL;
	NSError *theError = NULL;
	NSString *stat;
	NSData *theResponseData;
	NSString *theResponseString;
	
	// Try 2 times to send the file on the server, useful when on EDGE. The connection seems to drop sometimes.
	for (i = 0; i < 2; i++ )
	{
		if(i >0)
		{
			[theResponseString release];
		}
		
		theResponseData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&theResponse error:&theError];
		theResponseString = [[NSString alloc] initWithData:theResponseData encoding:NSASCIIStringEncoding];
		
		if([theResponseString length] == 0)
		{
			[theResponseString release];
			theResponseString = [[NSString alloc] initWithCString:"CONNECTION ERROR" encoding:NSASCIIStringEncoding];
		}
		
		//NSLog(@"response  is (%@)", theResponseString);
		
		@try
		{
			stat = [theResponseString substringToIndex: 2];
			
			if([stat isEqualToString: @"OK"])
			{
				break;
			}
			else if( ([stat isEqualToString: @"LO"] || [stat isEqualToString: @"FA"]) && [stat length] >= 11)
			{
				stat = [theResponseString substringToIndex: 11];
				
				if([stat isEqualToString: @"LOGIN ERROR"] || [stat isEqualToString: @"FATAL ERROR"])
				{
					break;
				}
			}
		}
		@catch (NSException *exception)
		{
			stat = @"";
			NSLog(@"NSException caught in extracting substring");
		}
	}
	
	//[theResponseString release];
	[theURL release];
	
	//[stat retain];
	return theResponseString;
	
	//[mainView setText:stat];
	/* All retries exhausted...	*/
	/*if (![stat isEqualToString:@"OK"]) 
	{
		//NSLog(@"Upload failed");
		return 0;
	}
	
	return 1;*/
}

@end